<template>
  <q-stepper v-if="display" v-model="steps" :active-icon="activeIcon" active-color="primary"
             class="q-pt-sm q-pb-sm text-bold" flat header-nav @update:model-value="updateSteps">
    <q-step v-for="menu in menus" :key="menu.path" :icon="icon(menu.meta)" :name="menuKey(menu)"
            :title="menuName(menu.meta)"></q-step>
  </q-stepper>
</template>

<script setup>
import { toI18nName } from 'boot/i18n'
import { userStores } from 'stores/user-stores'
import { computed, inject, nextTick, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const steps = ref('')
const userStore = userStores()
const handleLoad = inject('handleLoad')
const isXS = inject('isXS', false)
const menus = computed(() => userStore.treeMenus)
const icon = computed(() => (meta = {}) => meta.menuIcon || 'storage')
const menuName = (meta = {}) => meta[toI18nName('menuZhCn')] || meta.title
const menuKey = computed(() => (menu = {}) => menu.meta?.menuId || menu.path)
const activeIcon = computed(() => {
  const menu = menus.value.find(el => menuKey.value(el) === steps.value) || {}
  return icon.value(menu.meta)
})
const display = computed(() => userStore.breadcrumbs?.serviceCode === 'amr-model-api')
const parentIds = computed(() => ((route.meta || {}).parentIds || '').split(','))
watch(parentIds, ids => {
  const menu = menus.value.find(el => ids.includes((el.meta || {}).menuId)) || {}
  steps.value = menuKey.value(menu)
}, { immediate: true })

const skipPath = path => {
  if (path === route.fullPath) return
  handleLoad(true)
  nextTick(async () => {
    await router.replace(path)
    handleLoad(false)
  })
}
const updateSteps = e => {
  const menu = menus.value.find(el => menuKey.value(el) === e) || {}
  if (menu.children && menu.children.length) skipPath(menu.children[0].path)
}
</script>
<style lang="scss" scoped>
.q-stepper {
  padding-left: v-bind('`${isXS ? "" : "10%"}`');
  padding-right: v-bind('`${isXS ? "" : "10%"}`');
}

.q-stepper--horizontal .q-stepper__step-inner {
  padding: 0;
}

.q-stepper:deep(.q-stepper__tab) {
  color: $dark;
  min-height: 36px;
  border-radius: 4px;

  .q-stepper__dot {
    margin-right: 2px;
    font-size: 1.5rem;
    background-color: transparent;

    i {
      color: $grey-6;
    }
  }
}

.q-stepper:deep(.q-stepper__tab--active) {
  &::before {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    content: '';
    opacity: .1;
    background-color: var(--q-primary);
  }

  .q-stepper__dot {
    background-color: transparent;

    i {
      color: var(--q-primary);
    }

  }
}

.q-stepper:deep(.q-stepper__content) {
  display: none;
}
</style>